// Learn cc.Class:
//  - https://docs.cocos.com/creator/manual/en/scripting/class.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

import global from './global'
cc.Class({
    extends: cc.Component,

    properties: {
        atlas: {
            type: cc.SpriteAtlas,
            default: null
        },
        boomFrame: {
            type: [cc.SpriteFrame],
            default: []
        }
        // foo: {
        //     // ATTRIBUTES:
        //     default: null,        // The default value will be used only when the component attaching
        //                           // to a node for the first time
        //     type: cc.SpriteFrame, // optional, default is typeof default
        //     serializable: true,   // optional, default is true
        // },
        // bar: {
        //     get () {
        //         return this._bar;
        //     },
        //     set (value) {
        //         this._bar = value;
        //     }
        // },
    },

    // LIFE-CYCLE CALLBACKS:

    onLoad () {
        this.changeType(global.FruitType)
    },

    changeType(type) {
        let atlas = this.atlas.getSpriteFrames()[type];
        let sprite = this.node.addComponent(cc.Sprite);
        sprite.spriteFrame = atlas;
        
        
        let physics = this.node.getComponent(cc.PhysicsCircleCollider);
        physics.radius = this.node.width/2;
        physics.tag = type;
        physics.apply();

    },
    // 只在两个碰撞体开始接触时被调用一次
    onEndContact: function (contact, selfCollider, otherCollider) {
        if(selfCollider.tag === otherCollider.tag) {
           if(selfCollider.node.y < otherCollider.node.y) {
                otherCollider.node.destroy();
                this.boomFruit(selfCollider.tag);
           }
        }
    },
    boomFruit(tag) {
        let sprite = this.node.getComponent(cc.Sprite);
        sprite.spriteFrame = this.boomFrame[tag]
        this.scheduleOnce(_=>{
            // this.node.destroy();
            this.changeType(tag + 1);
            global.SCORE += (tag + 1) * 2;
            cc.sys.localStorage.setItem('score', global.SCORE);
            this.node.parent.emit('addScore')
        }, 0.15)
    }
});
